package playnsimple.core;

import static playn.core.PlayN.*;

import org.jbox2d.common.Vec2;

import playn.core.Game;
import playn.core.GroupLayer;
import playn.core.PlayN;

import playnsimple.core.conf.DeviceConf;
import playnsimple.core.state.EndState;
import playnsimple.core.state.HomeState;
import playnsimple.core.state.PlayState;
import playnsimple.core.state.StateMachine;



public class PlaynSimple implements Game {
    
    // Program State Manager
    private StateMachine stateMachine;
    
    // PlayN Object / Services
    private GroupLayer rootLayer = graphics().rootLayer();
    public static Vec2 windowSize = new Vec2(graphics().width(),
            graphics().height());
    
    // Other Constants
    int FRAMES_PER_SEC = 30;
    
    /*
     * Game Methods
     */
    @Override
    public void init() {
        initStateMachine();
        initEventHandler();
    }
    
    private void initStateMachine() {
        stateMachine = new StateMachine();
        
        // Init states
        HomeState homeState = new HomeState("home");
        PlayState playState = new PlayState("play");
        EndState endState = new EndState("end");
        
        // Add states
        stateMachine.addState(homeState);
        stateMachine.addState(playState);
        stateMachine.addState(endState);
        
        // Set state
        stateMachine.changeState("home");
    }
    
    private void initEventHandler() {
        // TODO Auto-generated method stub
        
    }


    @Override
    public void paint(float alpha) {
        graphics().rootLayer().clear();
        stateMachine.paint();
    }
    
    @Override
    public void update(float delta) {
        if (stateMachine.isRunning()) {
            stateMachine.update();
        }
    }
    
    @Override
    public int updateRate() {
        // MS / FRAME
        return (int) Math.round(1000.0 / FRAMES_PER_SEC);
    }
    
    
    /*
     * Debug Methods
     */
    public static int sortCount;

    public static void brk() {
        throw new IllegalStateException("break");        
    }
    
    public static void brk(Object object) {
        log(object);
        throw new IllegalStateException("break");        
    }
    
    public static void log(Object object) {
        if ( object == null ) {
            object = "<NULL>";
        }
        String message = object.toString();
        PlayN.log().info(message);
    }

}
